package com.lc.config;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JwtToken工具类
 */
@Component
public class JwtTokenUtil {

    public static final String CLAIM_KEY_USERNAME = "sub";
    public static final String CLAIM_KEY_CREATED = "created";

    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;


    /**
     * 根据用户信息生成token
     * @param userDetails
     * @return
     */
    public String generatorToken(UserDetails userDetails){
        Map<String,Object> claim = new HashMap<>();
        claim.put(CLAIM_KEY_USERNAME,userDetails.getUsername());
        claim.put(CLAIM_KEY_CREATED,new Date());
        return generatorToken(claim);
    }

    /**
     * 根据token获取登录的用户名
     * @param token
     * @return
     */
    public String getUsernameFromToken(String token){
        String username;
        try {
            Claims claims = getClaimFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 根据token获取claims
     * @param token
     * @return
     */
    private Claims getClaimFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            //过期的 Jwt 异常
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            //不受支持的 Jwt 异常
            e.printStackTrace();
        } catch (MalformedJwtException e) {
            //格式错误的 Jwt 异常
            e.printStackTrace();
        } catch (SignatureException e) {
            //签名异常
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            //非法参数异常
            e.printStackTrace();
        }
        return claims;
    }

    /**
     * 判断token是否失效
     * @param token
     * @param userDetails
     * @return
     */
    public boolean validateToken(String token,UserDetails userDetails){
        String username = getUsernameFromToken(token);
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }

    /**
     * 判断token有没有过期
     * @param token
     * @return
     */
    private boolean isTokenExpired(String token) {
        Date expiration = getExpirationFromToken(token);
        return expiration.before(new Date());
    }

    /**
     * 刷新token
     * @param token
     * @return
     */
    public String refreshToken(String token){
        Claims claim = getClaimFromToken(token);
        claim.put(CLAIM_KEY_CREATED,new Date());
        return generatorToken(claim);
    }

    /**
     * 判断token是否可以被刷新
     * @param token
     * @return
     */
    public boolean canRefresh(String token){
        return !isTokenExpired(token);
    }

    /**
     * 获取token过期时间
     * @param token
     * @return
     */
    private Date getExpirationFromToken(String token) {
        Claims claimFromToken = getClaimFromToken(token);
        return claimFromToken.getExpiration();
    }

    /**
     * 根据荷载生成token
     * @param claim
     * @return
     */
    private String generatorToken(Map<String, Object> claim) {
        return Jwts.builder()
                //设置声明
                .setClaims(claim)
                //设置过期
                .setExpiration(generatorExpirationDate())
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    /**
     * 设置token过期时间
     * @return
     */
    private Date generatorExpirationDate() {
        //返回当前系统生成token的时间加上设置的过期有效时间
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

}
